﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Transactions;
using CarHelpDesk.Web.Utils;


namespace CarHelpDesk.Web.Models.Repositories.LinqRepositories
{
    public class QuestionVotesRepository :IQuestionVotesRepository
    {
        #region Constants
        
        private static readonly int VOTE_UP_VALUE = 10;
        private static readonly int VOTE_DOWN_VALUE = -2;

        #endregion

        #region Fields

        private LinqModelDataContext _db;
        
        #endregion

        #region Constructors

        public QuestionVotesRepository()
        {
            _db = new LinqModelDataContext();
#if DEBUG
            _db.Log = DebugTextWriter.Instance;
#endif
        }

        #endregion

        #region IQuestionVotesRepository Members

        public bool GetVote(int questionID, Guid userID, out QuestionVote result)
        {
            var votes = from vote in _db.QuestionVotes
                    where vote.QuestionID == questionID && vote.UserID == userID
                    select vote;

            Debug.Assert(votes.Count() <= 1, "There cannot be more then one vote with same QuestionID and UserID");

            if (votes.Count() == 1)
            {
                result = votes.First();
                return true;
            }
            else
            {
                result = null;
                return false;
            }
        }

        public void CreateVote(QuestionVote vote)
        {
            using (var transaction = new TransactionScope())
            {
                _db.QuestionVotes.InsertOnSubmit(vote);
                _db.SubmitChanges();

                if (vote.VoteValue == 1)
                {
                    vote.Question.VoteUpCount++;
                    vote.Question.aspnet_User.UserDetail.UserRating += VOTE_UP_VALUE;
                }
                else if (vote.VoteValue == -1)
                {
                    vote.Question.VoteDownCount ++ ;
                    vote.Question.aspnet_User.UserDetail.UserRating += VOTE_DOWN_VALUE;
                }
                else
                {
                    throw new ArgumentException("VoteValue should be 1 or -1", "VoteValue");
                }

                _db.SubmitChanges();
                transaction.Complete();
            }
        }

        public void UpdateVote(QuestionVote vote)
        {
            throw new NotImplementedException();
        }

        public IQueryable<QuestionVote> GetAllUserVotes(Guid userID)
        {
            throw new NotImplementedException();
        }

        public IQueryable<QuestionVote> GetAllQuestionsVotes(int questionID)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
